/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import Facade.AccountFacadeLocal;
import Facade.CustomerFacadeLocal;
import Facade.ManagerLocal;
import entity.CurrencyEE;
import entity.Customer;
import exceptions.LoginAlreadyExistsException;
import java.math.BigDecimal;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.faces.component.html.HtmlInputHidden;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import util.JsfUtil;

/**
 *
 * @author Vojtisek
 */
public class CustomerManagedBean {

    @EJB
    private ManagerLocal managerBean;
    @EJB
    private AccountFacadeLocal accountFacade;
    @EJB
    private CustomerFacadeLocal customerFacade;
    private String login;
    private String firstName;
    private String lastName;
    private String password;
    private Integer customerId;
    private Integer accountId;
    HtmlInputHidden inputHidden;
    private static final Logger logger = Logger.getLogger("CustomerManagedBean");
    private Customer customer;
    private BigDecimal limit;
    private CurrencyEE currencyLimit;

    public boolean getInitCustomerDetails() {
        try {
            Customer c = customerFacade.getCustomer();
            if (c != null) {
                login = c.getLogin();
                firstName = c.getFirstName();
                lastName = c.getLastName();
                customerId = c.getId();
                limit = c.getTransactionLimit();
                currencyLimit = c.getCurrency();
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, "postconstruct exception");
        }
        return true;
    }

    public String logout() {
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        HttpSession session = (HttpSession) ec.getSession(true);
        session.invalidate();
        return "index";
    }

    public String create() {
        try {
            Customer cust = new Customer(login, password, firstName, lastName, limit, currencyLimit);
            managerBean.createCustomer(cust);
            JsfUtil.addSuccessMessage("Customer was successfully created.");
        } catch (LoginAlreadyExistsException e) {
            JsfUtil.addErrorMessage("Login already exists");
            logger.log(Level.SEVERE, e.getMessage(), e);
            return null;
        } catch (EJBException ef) {
            JsfUtil.addErrorMessage("EJBException");
            logger.log(Level.SEVERE, ef.getMessage(), ef);
            return null;
        } catch (Exception ex) {
            JsfUtil.ensureAddErrorMessage(ex, "Persistance error");
            logger.log(Level.SEVERE, ex.getMessage(), ex);
            return null;
        }
        return null;
    }

    public String edit() {
        try {
            managerBean.editCustomer(customerId, login, firstName, lastName, limit, currencyLimit);
            JsfUtil.addSuccessMessage("OK");
            String url = "viewDetails.jsp?customerId=" + customerId;
            FacesContext fc = FacesContext.getCurrentInstance();
            fc.getExternalContext().redirect(url);
            return null;

        } catch (LoginAlreadyExistsException e) {
            JsfUtil.addErrorMessage("Login already exists");
            logger.log(Level.SEVERE, "Customer edit: Login already exists: " + login);
        } catch (Exception ex) {
            JsfUtil.addErrorMessage(ex.getMessage());
            logger.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return null;

    }

    public Collection<Customer> getList() {
        try {
            return managerBean.getAllCustomers();
        } catch (Exception ex) {
            JsfUtil.addErrorMessage("Error while loading cusomer list");
            logger.log(Level.SEVERE, ex.getMessage(), ex);
            return null;
        }
    }

    public void setAccountId(Integer accountId) {
        this.accountId = accountId;
        if (accountId != null && customerId == null) {
            try {
                customerId = managerBean.getAccount(accountId).getOwner().getId();
                customer = managerBean.getCustomer(customerId);
                login = customer.getLogin();
                firstName = customer.getFirstName();
                lastName = customer.getLastName();
                limit = customer.getTransactionLimit();
                currencyLimit = customer.getCurrency();
                return;
            } catch (Exception e) {
                JsfUtil.ensureAddErrorMessage(e, "Persistance error: " + e.toString());
                logger.log(Level.SEVERE, "setCustomerId" + e.getMessage(), e);
            }
        }
    }

    public void setCustomerId(Integer customerId) {
        try {
            logger.log(Level.SEVERE, "setCustomerId " + customerId);
            if (customerId != null) {
                this.customerId = customerId;
                customer = managerBean.getCustomer(customerId);
                login = customer.getLogin();
                firstName = customer.getFirstName();
                lastName = customer.getLastName();
                limit = customer.getTransactionLimit();
            }
            return;
        } catch (Exception e) {
            JsfUtil.ensureAddErrorMessage(e, "Persistance error: " + e.toString());
            logger.log(Level.SEVERE, "setCustomerId" + e.getMessage(), e);
        }
    }
//    public Collection<SelectItem> getCustomerChoices() {
//        try {
//            Collection<SelectItem> choices = new ArrayList<SelectItem>();
//            for (Customer d : customerFacade.findAll()) {
//                choices.add(new SelectItem(d.getId(), d.getId().toString()));
//            }
//            return choices;
//        } catch (Exception ex) {
//            JsfUtil.ensureAddErrorMessage(ex, "Error while loading customers");
//            logger.log(Level.SEVERE, ex.getMessage(), ex);
//            return null;
//        }
//    }
//    public void remove(Customer customer) {
//        try {
//            customerFacade.remove(customer);
//        } catch (Exception ex) {
//            logger.log(Level.SEVERE, ex.getMessage(), ex);
//        }
//    }

    public Customer findCustomer(Integer id) throws Exception {
        return managerBean.getCustomer(id);
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAccountId() {
        return accountId;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public Integer getCustomerId() {
        return customerId;
    }

    public HtmlInputHidden getInputHidden() {
        return inputHidden;
    }

    public String getPassword() {
        return password;
    }

    public BigDecimal getLimit() {
        return limit;
    }

    public void setLimit(BigDecimal limit) {
        this.limit = limit;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setInputHidden(HtmlInputHidden inputHidden) {
        this.inputHidden = inputHidden;
    }

    public CurrencyEE getCurrencyLimit() {
        return currencyLimit;
    }

    public void setCurrencyLimit(CurrencyEE currencyLimit) {
        this.currencyLimit = currencyLimit;
    }
}
